package com.gcc.notes.securenotes.service;


import com.gcc.notes.securenotes.model.Note;
import com.gcc.notes.securenotes.model.User;
import com.gcc.notes.securenotes.repository.NoteRepository;
import com.gcc.notes.securenotes.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class NoteServiceImpl implements NoteService {

    private final NoteService noteReposity;
    private final UserRepository userRepository;

@Autowired
public NoteServiceImpl(NoteRepository noteRepository, UserRepository userRepository) {
    this.noteReposity = noteRepository;
    this.userRepository = userRepository;
}

@Override
    public List<Note> findAllUserNotes(String username) {
    User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("用户未找到或未登录：" + username));

    return noteReposity.findByUserIdOrderByUpdatedAtDesc(user.getId());
    }

@Override
public Optional<Note> findByIdAndOwner(Long id, String username) {
    Long userId = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("用户未找到：" + username))
            .getId();

    return noteReposity.findByIdAndUserId(id, userId);
}

@Override
    public Note saveNewNote(Note note, String username) {
    User user = userRepository.findByUsername(username)
            .orElseThrow(() -> new UsernameNotFoundException("用户未找到：" + username));

    note.setUser(user);
    return noteReposity.save(note);
    }

    @Override
    public Note updateNote(Note note, String username) {
        Note existingNote = noteReposity.findByIdAndUserId(note.getId(), user.getId())
                .orElseThrow(() -> new NoteNotFoundException("笔记未找到或您没有权限编辑。"));

        existingNote.setTitle(note.getTitle());
        existingNote.setContent(note.getContent());

        return noteReposity.save(existingNote);
    }

@Override
public void deleteNote(Long id, String username) {
    Note noteToDelete = findByIdAndUserId(id, username)
            .orElseThrow(() -> new NoteNotFoundException("笔记未找到或您没有权限删除。"));

    noteReposity.delete(noteToDelete);
}
}
